package main.java.Fzy.Demo.MyThread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class testThread {


    public static void main(String[] args) throws Exception {

        //实现方式一
        Thread thread1 = new CreatedThreadOne();
        thread1.start();

        //实现方式二
        CreatedThreadTwo createdThreadTwo = new CreatedThreadTwo();
        Thread thread2 = new Thread(createdThreadTwo);
        thread2.start();



        //实现方式三
        //创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);


        //创建多个有返回值的任务列表
        List<Future> list = new ArrayList<Future>();

        /**
         * Future接口 : 异步执行的结果,返回的结果将会保存在future中
        */

        for(int i =0;i<5;i++){
            //创建有返回值的线程实例
            Callable callable = new CreatedThreadThree(i+" ");
            //提交线程，获取Future对象并将其保存到Future List中
            Future future = pool.submit(callable);
            System.out.println("submit a callable thread :" + i);
            Thread.sleep(1000);
            list.add(future);

        }

        //关闭线程池
        pool.shutdown();
        //遍历所有线程的运行结果
        for(Future future : list){
            //从Future对象上获取任务的返回值,并将结果打印
            System.out.println("get the result from callable thread"+future.get().toString());
        }

        //实现方式四
        ExecutorService createPool = Executors.newFixedThreadPool(10);

        for(int i = 0;i<10;i++){
            //提交多个线程任务执行
            createPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"is running");
                }
            });
        }

    }

}
